package com.yksj.healthtalk.ui.home;

import org.handmark.pulltorefresh.library.PullToRefreshScrollView;
import org.json.JSONArray;
import org.universalimageloader.core.ImageLoader;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.TickMesg;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorCommonServiceActivity.BUTTON;
import com.yksj.healthtalk.ui.doctor.DoctorServiceActivity;
import com.yksj.healthtalk.ui.home.MyDoctorTimePayActivity.AsyncHander;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.JsonParseUtils;
import com.yksj.healthtalk.utils.TimeUtil;
import com.yksj.healthtalk.utils.ToastUtil;

public class MyDoctorInterviewPayActivity extends BaseFragmentActivity implements OnClickListener, OnDilaogClickListener{
	
	private static final int REQUESTCODE = 0;
	private String mData;
	private CustomerInfoEntity mCustomerInfoEntity;
	private ImageView headIv;
	private ImageLoader mImageLoader;
	private TextView name;
	private TextView title_departments;
	private TextView hospital;
	private TextView address;
	private TextView special;
	private TextView money;
	private TextView time;
	private TextView content;
	private JSONObject mesgObject;
	private TickMesg mesg;
	private WithdrawingRegistrationFragment fragment2;
	private TextView mServcieAddress;
	private int id;
	private PullToRefreshScrollView scrollView;
	private int mClickBtnId;//判断点击的是哪个id的对话框
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.mydoctor_reservation);
		Intent intent = getIntent();
		mData = intent.getStringExtra("response");
		mCustomerInfoEntity = (CustomerInfoEntity) intent.getExtras().get("mCustomerInfoEntity");
		initWidget();
		initData();
	}

	private void initData() {
		
		try {
			JSONObject object = (JSONObject) JSON.parse(mData);
			mesgObject = object;
			mesg = (TickMesg) JSON.parseObject(object.toString(),TickMesg.class);
			money.setText(mesgObject.getString("SERVICE_GOLD")+"元");
			//所享受服务
			TextView textview=(TextView) findViewById(R.id.service_content1);
			textview.setText(object.getString("SERVICE_CONTENT"));
			 String timeSpace ;
			if (!TextUtils.isEmpty(timeSpace = FriendUtil.getTimeSpace(mesgObject.getString("SERVICE_START"),mesgObject.getString("SERVICE_END")))) {
				time.setText(timeSpace);
			}else {
				time.setText("");
			}
			content.setText(mesgObject.getString("ADVICE_CONTENT"));
			mServcieAddress.setText(mesgObject.getString("SERVICE_PLACE"));
			//预约服务开始时间>当前服务器系统时间 的判断标准    是否显示按钮
			if (id == 1) {//取消预约
				Button button = (Button)findViewById(R.id.delete);
				if (!TextUtils.isEmpty(mesg.getSYSTEMTIME()) && !TextUtils.isEmpty(mesg.getSERVICE_START()) &&TimeUtil.formatMillion(mesg.getSERVICE_START()) > TimeUtil.formatMillion(mesg.getSYSTEMTIME())&& TimeUtil.formatMillion(mesg.getSERVICE_START())< TimeUtil.formatMillion(mesg.getSYSTEMTIME() )+2*60*60*1000) {
					button.setVisibility(View.GONE);
				}else {
					button.setVisibility(View.VISIBLE);
					button.setText("取消预约");
					button.setBackgroundResource(R.drawable.orange_button_selector);
					button.setTextColor(getResources().getColorStateList(R.color.text_orange));
					findViewById(R.id.delete).setOnClickListener(this);
				}
			}else if(id == 6){
				Button button2 = (Button)findViewById(R.id.delete);//指定--存入
				Button button = (Button)findViewById(R.id.pay);//存入--支付宝
				Button button3 = (Button)findViewById(R.id.pay2);//退到银行卡
				button2.setId(BUTTON.wallet.getId());
				if (!TextUtils.isEmpty(mCustomerInfoEntity.getServiceStatusCode())) {
					int code = Integer.valueOf(mCustomerInfoEntity.getServiceStatusCode());
					if (code == 222||code == 175 || code == 180) {
						button2.setText("存入钱包");
						button2.setBackgroundResource(R.drawable.login_button);
						button2.setTextColor(getResources().getColorStateList(R.color.text_green));
						button3.setVisibility(View.VISIBLE);
						button3.setText("退款到银行卡");
						button3.setBackgroundResource(R.drawable.login_out_btn_selector);
						button3.setTextColor(getResources().getColorStateList(R.color.text_blue));
						button.setText("退款到支付宝");
						button.setBackgroundResource(R.drawable.login_out_btn_selector);
						button.setTextColor(getResources().getColorStateList(R.color.text_blue));
						
						button.setVisibility(View.VISIBLE);
						button2.setVisibility(View.VISIBLE);
						button3.setVisibility(View.VISIBLE);
						button.setOnClickListener(this);
						button2.setOnClickListener(this);
						button3.setOnClickListener(this);
					}else {
						button.setVisibility(View.GONE);
						button2.setVisibility(View.GONE);
						button3.setVisibility(View.GONE);
					}
				}
			}
		} catch (Exception e) {
			finish();
			return;
		}
		
		titleTextV.setText("门诊预约服务");
		//头像
		mImageLoader = ImageLoader.getInstance();
		mImageLoader.displayImage(mCustomerInfoEntity.getSex(),mCustomerInfoEntity.getNormalHeadIcon(), headIv);
		//昵称
		name.setText(mCustomerInfoEntity.getName());
		// 职称和科室
		String office2 = mCustomerInfoEntity.getOfficeName2();
		if (!TextUtils.isEmpty(office2)) {
			office2 = "," + office2;
		}
		if (!TextUtils.isEmpty(mCustomerInfoEntity.getOfficeName1())) {
			title_departments.setText(mCustomerInfoEntity.getDoctorTitle()+ "/" + mCustomerInfoEntity.getOfficeName1() + office2);
		} else {
			title_departments.setText(mCustomerInfoEntity.getDoctorTitle());
		}
		// 医院
		hospital.setText(mCustomerInfoEntity.getHospital());
		// 地址
		if (!TextUtils.isEmpty(mCustomerInfoEntity.getDoctorWorkaddress())) {
			address.setText(mCustomerInfoEntity.getDoctorWorkaddress());
		}else {
			address.setText("");
		}
		// 描述
//		note.setText(mCustomerInfoEntity.getDescription());
		//专长
		if (!TextUtils.isEmpty(mCustomerInfoEntity.getSpecial())) {
			StringBuilder b = new StringBuilder();
			b.append("专长").append("\n").append(mCustomerInfoEntity.getSpecial());
			SpannableStringBuilder builder = new SpannableStringBuilder(b.toString());
			builder.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 2,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			builder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.tag_note)), 2, b.toString().length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			special.setText(builder);
		} else {
			special.setText("专长");
		}
		
		//按钮的显示
		if (!TextUtils.isEmpty(mCustomerInfoEntity.getServiceStatusCode())) {
			FriendUtil.isVisibleButtons(mCustomerInfoEntity,mesg,Integer.valueOf(mCustomerInfoEntity.getServiceStatusCode()), (LinearLayout)findViewById(R.id.buttons_lin),(TextView)findViewById(R.id.message_content),(TextView)findViewById(R.id.message),id);
		}
		
	}

	private void initWidget() {
		initTitle();
		scrollView = ((PullToRefreshScrollView) findViewById(R.id.hall));
		scrollView.setLayoutInvisible();
		headIv = (ImageView) findViewById(R.id.info_head);
		name = (TextView)findViewById(R.id.info_name);
		title_departments  = (TextView)findViewById(R.id.title_departments);
		hospital = (TextView)findViewById(R.id.hospital);
		address = (TextView)findViewById(R.id.address);
		special = (TextView)findViewById(R.id.special);
		money = (TextView)findViewById(R.id.money);
		time = (TextView)findViewById(R.id.time);
		content = (TextView)findViewById(R.id.content);
		mServcieAddress = (TextView)findViewById(R.id.servcie_address);
		
		if (getIntent().hasExtra("id")) {
			id = getIntent().getExtras().getInt("id");
			if (id == 1) {//取消预约
				findViewById(R.id.pay).setVisibility(View.GONE);
			}else if(id == 5){//支付失败
				findViewById(R.id.delete).setVisibility(View.GONE);
				findViewById(R.id.pay).setVisibility(View.GONE);
			}else {//查看详情
				findViewById(R.id.buttons_lin).setVisibility(View.VISIBLE);
				findViewById(R.id.delete).setVisibility(View.GONE);
				findViewById(R.id.pay).setVisibility(View.GONE);
			}
		}
		titleLeftBtn.setOnClickListener(this);
		findViewById(R.id.talk).setOnClickListener(this);
		findViewById(R.id.delay_time).setOnClickListener(this);
		findViewById(R.id.alert_doctors).setOnClickListener(this);
		findViewById(R.id.unsubscribe_service).setOnClickListener(this);
		
		
		titleRightBtn2.setText(R.string.sure);
		findViewById(R.id.address_lin).setVisibility(View.VISIBLE);
		
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == BUTTON.wallet.getId()) {
			mClickBtnId = BUTTON.wallet.getId();
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "为了您的账户安全，存入钱包后请绑定手机并设置支付密码。您确定将服务金额（"+(mesg.getSERVICE_PRICE() != null?mesg.getSERVICE_PRICE():mesg.getSERVICE_GOLD())+"元）存入钱包吗？", "放弃", "确定", this);
			return;
		}
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.delete:
			if (id == 1) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), CommonExplainActivity.class);
				intent.putExtra("title", "取消原因");
				intent.putExtra("mContentCount", 200); // 字数限制 默认是200
				startActivityForResult(intent, REQUESTCODE);
			}
			break;
		case R.id.pay://支付宝
			if (!TextUtils.isEmpty(mCustomerInfoEntity.getServiceStatusCode())&&id==6) {
				int code = Integer.valueOf(mCustomerInfoEntity.getServiceStatusCode());
				if (code == 175 || code == 180 || code == 222) {
					HttpRestClient.doHttpRefundOrWatch(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), mCustomerInfoEntity.getOrderId(), "Refund", new AsyncHander(id, "Refund",mCustomerInfoEntity.getOrderId(),mCustomerInfoEntity.getId()));
				}
			}
			break;	
		case R.id.pay2://银行卡
			if (!TextUtils.isEmpty(mCustomerInfoEntity.getServiceStatusCode())) {
			int code = Integer.valueOf(mCustomerInfoEntity.getServiceStatusCode());
			if (code == 175 || code == 180 || code == 222) {
				HttpRestClient.doHttpRefundOrWatch(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), mCustomerInfoEntity.getOrderId(), "Refund410", new AsyncHander(id, "Refund",mCustomerInfoEntity.getOrderId(),mCustomerInfoEntity.getId()));
			}
		}
		case R.id.talk:
			FriendHttpUtil.onItemClick(MyDoctorInterviewPayActivity.this, mCustomerInfoEntity);
			break;
		case R.id.delay_time:
			mClickBtnId = R.id.delay_time;
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  getString(R.string.customer_time_message), "取消", "确定", this);
			break;
		case R.id.alert_doctors:
			HttpRestClient.doHttpRemindDoctor(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(),mesg.getORDER_ID(),new AsyncHander(BUTTON.alert.getId()));
			break;
		case R.id.unsubscribe_service:
			HttpRestClient.doHttpServiceSetServlet(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(),mesg.getORDER_ID(), new AsyncHander(BUTTON.unsubscribe.getId()));
			break;
		default:
			break;
		}
	}
	
	
	public void onClickServiceContent(View v){
		Intent intent = new Intent(getApplicationContext(),DoctorServiceActivity.class);
		if (mesg != null) {
			intent.putExtra("ORIDERID",mesg.getORDER_ID());
		}else {
			return;
		}
		intent.putExtra("isbuy", true);
		startActivity(intent);
	}
	
	
	class AsyncHander extends  AsyncHttpResponseHandler{
		
		private int ButtonId;
		private String type;
		private String payid;
		private String doctorId;
		private int id;
		

		public AsyncHander(int id) {
			super(MyDoctorInterviewPayActivity.this);
			this.ButtonId = id;
		}

		public AsyncHander(int id,String type,String payid,String doctorId) {
			super(MyDoctorInterviewPayActivity.this);
			this.type = type;
			this.payid = payid;
			this.doctorId = doctorId;
			this.id = id;
		}
		
		@Override
		public void onSuccess(int statusCode, String content) {
			try {
				Object object = JSON.parse(content);
				if (object == null && ButtonId == BUTTON.delete.getId()) {//删除订单
					ToastUtil.showShort(getApplicationContext(), "删除订单成功");
					finish();
				}else if (object == null && ButtonId == BUTTON.alert.getId()) {//提醒医生
					ToastUtil.showShort(getApplicationContext(), getString(R.string.customer_alert_message));
					finish();
				} else if (object instanceof JSONObject) {
					JSONObject object2 = (JSONObject) object;
					if (object2.containsKey("error_message")) {
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), object2.getString("error_message"));
						return;
					}else if (id== 6 && ButtonId != BUTTON.wallet.getId()) {//支付失败服务
						// 申请退款（退款）
						if (type.equalsIgnoreCase("Refund")) {
							if (object2.containsKey("PAY_ACCOUNT")) {
								Intent intent = new Intent(getApplicationContext(),RefundActivity.class);
								Bundle bundle = new Bundle();
								bundle.putString("account", object2.getString("PAY_ACCOUNT"));
								bundle.putString("payId", payid);
								bundle.putString("tel", object2.getString("TRANSFER_GETTELE"));
								bundle.putString("customerId", doctorId);
								bundle.putBoolean("bankcard", false);
								intent.putExtras(bundle);
								startActivity(intent);
								finish();
								}else if(object2.containsKey("TRANSFER_CODE")){
								Intent intent = new Intent(getApplicationContext(),RefundActivity.class);
								Bundle bundle = new Bundle();
								bundle.putString("account",	object2.getString("TRANSFER_CODE"));
								bundle.putString("openbank",	object2.getString("TRANSFER_NAME"));
								bundle.putString("tel",object2.getString("TRANSFER_GETTELE"));
								bundle.putString("customerId", doctorId);
								bundle.putString("payId", payid);
								bundle.putBoolean("bankcard", true);
								intent.putExtras(bundle);
								startActivity(intent);
								finish();
								}
							}else if (type.equalsIgnoreCase("ViewRefunds")) {//填写 退款信息
								// {"PAY_ACCOUNT":"1","ORDER_UPDATE_TIME":"20130923155508","PAY_ID":"130920007144600","TRANSFER_GETTELE":"ss","PAY_OK_TIME":null,"SERVICE_END":null,"TRANSACTION_ID":"2013092055619153","NOTE":null,"SERVICE_FEEDBACK":null,"SERVICE_GOLD":1,"SERVICE_STATUS":232,"ENJOY_CUSTOMER_ID":133585,"ORDER_ID":1222,"SERVICE_ALREADY":"N","FEEDBACK_TIME":null,"ORDER_CLASS_ID":10,"PAY_TYPE_ID":null,"SERVICE_CUSTOMER_ID":132871,"ORDER_CREATE_TIME":"20130920144627","MERCHANT_ID":null,"SERVICE_START":null}
								Intent intent = new Intent(getApplicationContext(),ToSeeRefundActivity.class);
								Bundle bundle = new Bundle();
								if (object2.containsKey("PAY_ACCOUNT")) {
									bundle.putString("account", object2.getString("PAY_ACCOUNT"));
									bundle.putString("tel", object2.getString("TRANSFER_GETTELE"));
								}
								intent.putExtras(bundle);
								startActivity(intent);
							}
						} else if(object2.containsKey("LING") && ButtonId == BUTTON.pay.getId()){//价格为0 跳转到 聊天界面
							FriendHttpUtil.onItemClick(MyDoctorInterviewPayActivity.this, mCustomerInfoEntity);
					}else if(ButtonId == BUTTON.unsubscribe.getId()){//退订服务
						if (object2.containsKey("PAY_ACCOUNT")) {
							// 绑定的手机号码
							String payAccount = object2.getString("PAY_ACCOUNT");
							String tel = object2.getString("TRANSFER_GETTELE");
							FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
							fragment2 = (WithdrawingRegistrationFragment) WithdrawingRegistrationFragment.getInstance(mCustomerInfoEntity,payAccount, tel,mesg.getORDER_ID());
							transaction.add(android.R.id.content, fragment2);
							transaction.addToBackStack(null);
							transaction.commitAllowingStateLoss();
						}
					}else if (ButtonId == BUTTON.Time.getId()) {
						ToastUtil.showShort(getApplicationContext(),"请求延时成功...");
						finish();
					} else if (ButtonId == BUTTON.alert.getId()) {
						SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), object2.getString("message"));
					}else if(ButtonId == BUTTON.wallet.getId()){
						finish();
					}
				}
			} catch (Exception e) {
				}
			super.onSuccess(statusCode, content);
		}

	}

	@Override
	public void onBackPressed() {
		if (getSupportFragmentManager().getBackStackEntryCount() >0) {
			getSupportFragmentManager().popBackStackImmediate();
			refresh();
		} else {
			finish();
		}
	}

	@Override
	public void onDismiss(DialogFragment fragment) {
	}
	
	@Override
	public void onClick(DialogFragment fragment, View v) {
		if (mClickBtnId == BUTTON.wallet.getId()) {
			if (mesg != null) {
			HttpRestClient.doHttpRefundWallet(mCustomerInfoEntity.getOrderId(), new AsyncHander(BUTTON.wallet.getId()) );
		}
		}else {
			HttpRestClient.doHttpDelayed(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(),mesg.getORDER_ID(), new AsyncHander(BUTTON.Time.getId()));
		}
	}
	
	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		if (arg0 == REQUESTCODE && arg1 == RESULT_OK) {
			if (arg2.hasExtra("content")) {
				HttpRestClient.doHttpCanceleservation(SmartFoxClient.getLoginUserId(), mCustomerInfoEntity.getId(), mesg.getORDER_ID(), arg2.getExtras().getString("content"), new JsonHttpResponseHandler(this){
					
					@Override
					public void onSuccess(int statusCode,org.json.JSONObject response) {
						if (JsonParseUtils.filterErrorMessage(response.toString()) == null) {
							ToastUtil.showShort(getApplicationContext(), "取消预约成功...");
							finish();
						}else {
							SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  JsonParseUtils.filterErrorMessage(response.toString()) );
						}
						super.onSuccess(statusCode, response);
					}
				});
			}
		}
		super.onActivityResult(arg0, arg1, arg2);
	}

	
	
	/**
	 * 重新请求界面
	 */
	private void refresh() {
		HttpRestClient.doHttpMyDoctorOrderDetail(SmartFoxClient.getLoginUserId(), mesg.getORDER_ID(), mCustomerInfoEntity.getId(), 
				new JsonsfHttpResponseHandler(this){
			@Override
			public void onStart() {
				scrollView.setLayoutVisible();
				scrollView.setRefreshing();
				super.onStart();
			}
			
			@Override
			public void onFinish() {
				scrollView.setLayoutInvisible();
				scrollView.onRefreshComplete();
				super.onFinish();
			}

			@Override
			public void onSuccess(int statusCode, JSONObject res) {
				if (JsonParseUtils.filterErrorMessage(res) == null) {
					mData = res.toString();
					initData();
				}else {
					ToastUtil.showShort(getApplicationContext(), JsonParseUtils.filterErrorMessage(res));
				}
				super.onSuccess(statusCode, res);
			}
			
		});
	}
	
}
